<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <script src="blockly/blockly_compressed.js"></script>
  <script src="blockly/blocks_compressed.js"></script>
  <script src="blockly/javascript_compressed.js"></script>
  <script src="blockly/msg/zh-hans.js"></script>

  <style>
    html,
    body,
    #blocklyDiv {
      height: 100%;
      width: 100%;
      overflow: hidden;
      margin: 0;
    }
  </style>
</head>

<body>
  <!-- <br> -->
  <div style="z-index: 100;position: fixed;bottom: 0;">

    <button onclick="showCode()">显示等效代码</button>
    <button onclick="runCode()">载入至闻达</button>
    <button onclick="saveCodeAsAuto()">保存至闻达</button>
    <button onclick="analyzeCode()">智能分析</button>
    <!-- <button
      onclick="localStorage['wenda_blockly_prog']=JSON.stringify(Blockly.serialization.workspaces.save(demoWorkspace))">
      保存</button>
    <button
      onclick="Blockly.serialization.workspaces.load(JSON.parse(localStorage['wenda_blockly_prog']), demoWorkspace)">
      读取</button> -->

    <button onclick="另存为(JSON.stringify(Blockly.serialization.workspaces.save(demoWorkspace)))">
      另存为</button>
    <input type="file" onchange="打开(this.files)"></input>

  </div>
  <div id="blocklyDiv" style="width: 100%;"></div>

  <script>
    另存为 = (stringData) => {
      const blob = new Blob([stringData], {
        type: "text/plain;charset=utf-8"
      })
      const objectURL = URL.createObjectURL(blob)
      const aTag = document.createElement('a')
      aTag.href = objectURL
      aTag.download = Date.now() + ".wenda_cat"
      aTag.click()
      URL.revokeObjectURL(objectURL)
    }
    打开 = (files) => {
      var file = files[0];
      var reader = new FileReader();
      reader.onload = function (e) {
        var contents = e.target.result;
        console.log(contents)
        Blockly.serialization.workspaces.load(JSON.parse(contents), demoWorkspace)
        // 处理读取到的文件内容
        // ...
      };
      reader.readAsText(file);
    }
    // s = document.documentElement.clientHeight / 600;
    // document.body.style.zoom = s;
    Blockly.Blocks['发送'] = {
      init: function () {
        this.jsonInit({
          "message0": '发送 %1 至闻达',
          "args0": [
            {
              "type": "input_value",
              "name": "VALUE",
              "check": "String"
            }
          ],
          previousStatement: null,
          nextStatement: null,
          "output": "String",
          "colour": "purple",
          "tooltip": "发送",
        });
      }
    }
    Blockly.JavaScript['发送'] = function (block) {
      var argument0 = Blockly.JavaScript.valueToCode(block, 'VALUE',
        Blockly.JavaScript.ORDER_FUNCTION_CALL) || '\'\'';
      return ["await send(" + argument0 + ')', Blockly.JavaScript.ORDER_MEMBER];
    }
    Blockly.Blocks['添加用户会话'] = {
      init: function () {
        this.jsonInit({
          "message0": '添加用户会话 %1',
          "args0": [
            {
              "type": "input_value",
              "name": "VALUE"
            }
          ],
          previousStatement: null,
          nextStatement: null,
          "colour": "purple",
          "tooltip": "添加用户会话",
        });
      }
    }
    Blockly.JavaScript['添加用户会话'] = function (block) {
      var argument0 = Blockly.JavaScript.valueToCode(block, 'VALUE',
        Blockly.JavaScript.ORDER_FUNCTION_CALL) || '\'\'';
      return "add_conversation(\"user\"," + argument0 + ')\n';
    }
    Blockly.Blocks['使用知识库回答'] = {
      init: function () {
        this.jsonInit({
          "message0": '使用知识库回答 %1',
          "args0": [
            {
              "type": "input_value",
              "name": "VALUE"
            }
          ],
          previousStatement: null,
          nextStatement: null,
          "output": "String",
          "colour": "purple",
          "tooltip": "使用知识库回答",
        });
      }
    }
    Blockly.JavaScript['使用知识库回答'] = function (block) {
      var argument0 = Blockly.JavaScript.valueToCode(block, 'VALUE',
        Blockly.JavaScript.ORDER_FUNCTION_CALL) || '\'\'';
      return ["await answer_with_zsk(" + argument0 + ')\n', Blockly.JavaScript.ORDER_MEMBER];
    }
    Blockly.Blocks['使用快速知识库回答'] = {
      init: function () {
        this.jsonInit({
          "message0": '使用快速知识库回答 %1',
          "args0": [
            {
              "type": "input_value",
              "name": "VALUE"
            }
          ],
          previousStatement: null,
          nextStatement: null,
          "output": "String",
          "colour": "purple",
          "tooltip": "使用快速知识库回答",
        });
      }
    }
    Blockly.JavaScript['使用快速知识库回答'] = function (block) {
      var argument0 = Blockly.JavaScript.valueToCode(block, 'VALUE',
        Blockly.JavaScript.ORDER_FUNCTION_CALL) || '\'\'';
      return ["await answer_with_fast_zsk(" + argument0 + ')\n', Blockly.JavaScript.ORDER_MEMBER];
    }
    // { message0: module$contents$Blockly$libraryBlocks$texts_Msg.TEXT_PRINT_TITLE,
    //   args0: [{ type: "input_value", name: "TEXT" }],
    //    previousStatement: null,
    //     nextStatement: null, 
    //     style: "text_blocks",
    //      tooltip: module$contents$Blockly$libraryBlocks$texts_Msg.TEXT_PRINT_TOOLTIP, 
    //      helpUrl: module$contents$Blockly$libraryBlocks$texts_Msg.TEXT_PRINT_HELPURL }
    Blockly.Blocks['添加AI会话'] = {
      init: function () {
        this.jsonInit({
          "message0": '添加AI会话 %1',
          "args0": [
            {
              "type": "input_value",
              "name": "VALUE",
            }
          ],
          previousStatement: null,
          nextStatement: null,
          "colour": "purple",
          "tooltip": "添加AI会话",
        });
      }
    }
    Blockly.JavaScript['添加AI会话'] = function (block) {
      var argument0 = Blockly.JavaScript.valueToCode(block, 'VALUE',
        Blockly.JavaScript.ORDER_FUNCTION_CALL) || '\'\'';
      return "add_conversation(\"AI\"," + argument0 + ')\n';
    }
    Blockly.Blocks['用户输入'] = {
      init: function () {
        this.jsonInit({
          "message0": '用户输入',
          "args0": [
          ],
          "output": "String",
          "colour": "purple",
          "tooltip": "Returns number of letters in the provided text.",
        });
      }
    }
    Blockly.JavaScript['用户输入'] = function (block) {
      var argument0 = Blockly.JavaScript.valueToCode(block, 'VALUE',
        Blockly.JavaScript.ORDER_FUNCTION_CALL) || '\'\'';
      return ["get_user_input()", Blockly.JavaScript.ORDER_MEMBER];
    }
    var toolbox = {
      "kind": "categoryToolbox",
      "contents": [
        {
          "kind": "category",
          "name": "逻辑判断",
          "categorystyle": "logic_category",
          "contents": [
            {
              "kind": "block",
              "type": "controls_if"
            },
            {
              "kind": "block",
              "type": "controls_if",
              "extraState": {
                "hasElse": "true"
              }
            },
            {
              "kind": "block",
              "type": "controls_if",
              "extraState": {
                "hasElse": "true",
                "elseIfCount": 1
              }
            },
            {
              "kind": "block",
              "type": "logic_compare"
            },
            {
              "kind": "block",
              "type": "logic_operation"
            },
            {
              "kind": "block",
              "type": "logic_negate"
            },
            {
              "kind": "block",
              "type": "logic_boolean"
            },
            {
              "kind": "block",
              "type": "logic_null"
            },
            {
              "kind": "block",
              "type": "logic_ternary"
            }
          ]
        },
        {
          "kind": "category",
          "name": "循环",
          "categorystyle": "loop_category",
          "contents": [
            {
              "kind": "block",
              "type": "controls_repeat_ext",
              "inputs": {
                "TIMES": {
                  "block": {
                    "type": "math_number",
                    "fields": {
                      "NUM": 10
                    }
                  }
                }
              }
            },
            {
              "kind": "block",
              "type": "controls_whileUntil"
            },
            {
              "kind": "block",
              "type": "controls_for",
              "fields": {
                "VAR": "i"
              },
              "inputs": {
                "FROM": {
                  "block": {
                    "type": "math_number",
                    "fields": {
                      "NUM": 1
                    }
                  }
                },
                "TO": {
                  "block": {
                    "type": "math_number",
                    "fields": {
                      "NUM": 10
                    }
                  }
                },
                "BY": {
                  "block": {
                    "type": "math_number",
                    "fields": {
                      "NUM": 1
                    }
                  }
                }
              }
            },
            {
              "kind": "block",
              "type": "controls_forEach"
            },
            {
              "kind": "block",
              "type": "controls_flow_statements"
            }
          ]
        },
        {
          "kind": "category",
          "name": "数学计算",
          "categorystyle": "math_category",
          "contents": [
            {
              "kind": "block",
              "type": "math_number",
              "fields": {
                "NUM": 123
              }
            },
            {
              "kind": "block",
              "type": "math_arithmetic",
              "fields": {
                "OP": "ADD"
              }
            },
            {
              "kind": "block",
              "type": "math_single",
              "fields": {
                "OP": "ROOT"
              }
            },
            {
              "kind": "block",
              "type": "math_trig",
              "fields": {
                "OP": "SIN"
              }
            },
            {
              "kind": "block",
              "type": "math_constant",
              "fields": {
                "CONSTANT": "PI"
              }
            },
            {
              "kind": "block",
              "type": "math_number_property",
              "extraState": "<mutation divisor_input=\"false\"></mutation>",
              "fields": {
                "PROPERTY": "EVEN"
              }
            },
            {
              "kind": "block",
              "type": "math_round",
              "fields": {
                "OP": "ROUND"
              }
            },
            {
              "kind": "block",
              "type": "math_on_list",
              "extraState": "<mutation op=\"SUM\"></mutation>",
              "fields": {
                "OP": "SUM"
              }
            },
            {
              "kind": "block",
              "type": "math_modulo"
            },
            {
              "kind": "block",
              "type": "math_constrain",
              "inputs": {
                "LOW": {
                  "block": {
                    "type": "math_number",
                    "fields": {
                      "NUM": 1
                    }
                  }
                },
                "HIGH": {
                  "block": {
                    "type": "math_number",
                    "fields": {
                      "NUM": 100
                    }
                  }
                }
              }
            },
            {
              "kind": "block",
              "type": "math_random_int",
              "inputs": {
                "FROM": {
                  "block": {
                    "type": "math_number",
                    "fields": {
                      "NUM": 1
                    }
                  }
                },
                "TO": {
                  "block": {
                    "type": "math_number",
                    "fields": {
                      "NUM": 100
                    }
                  }
                }
              }
            },
            {
              "kind": "block",
              "type": "math_random_float"
            },
            {
              "kind": "block",
              "type": "math_atan2"
            }
          ]
        },
        {
          "kind": "category",
          "name": "文本处理",
          "categorystyle": "text_category",
          "contents": [
            {
              "kind": "block",
              "type": "text"
            },
            {
              "kind": "block",
              "type": "text_length"
            },
            {
              "kind": "block",
              "type": "text_print"
            }
          ]
        },

        {
          "kind": "sep"
        },
        {
          "kind": "category",
          "name": "列表",
          "categorystyle": "list_category",
          "contents": [
            {
              "kind": "block",
              "type": "lists_create_empty"
            },
            {
              "kind": "block",
              "type": "lists_create_with",
              "extraState": {
                "itemCount": 3
              }
            },
            {
              "kind": "block",
              "type": "lists_repeat",
              "inputs": {
                "NUM": {
                  "block": {
                    "type": "math_number",
                    "fields": {
                      "NUM": 5
                    }
                  }
                }
              }
            },
            {
              "kind": "block",
              "type": "lists_length"
            },
            {
              "kind": "block",
              "type": "lists_isEmpty"
            },
            {
              "kind": "block",
              "type": "lists_indexOf",
              "fields": {
                "END": "FIRST"
              }
            },
            {
              "kind": "block",
              "type": "lists_getIndex",
              "fields": {
                "MODE": "GET",
                "WHERE": "FROM_START"
              }
            },
            {
              "kind": "block",
              "type": "lists_setIndex",
              "fields": {
                "MODE": "SET",
                "WHERE": "FROM_START"
              }
            }
          ]
        },
        {
          "kind": "category",
          "name": "变量",
          "categorystyle": "variable_category",
          "custom": "VARIABLE"
        },
        {
          "kind": "category",
          "name": "函数",
          "categorystyle": "procedure_category",
          "custom": "PROCEDURE"
        },

        {
          "kind": "sep"
        },
        {
          "kind": "category",
          "name": "闻达",
          "colour": "purple",
          "contents": [
            {
              "kind": "block",
              "type": "发送"
            },
            {
              "kind": "block",
              "type": "用户输入"
            },
            {
              "kind": "block",
              "type": "添加用户会话"
            },
            {
              "kind": "block",
              "type": "添加AI会话"
            },
            {
              "kind": "block",
              "type": "使用知识库回答"
            },
            {
              "kind": "block",
              "type": "使用快速知识库回答"
            },
          ]
        }
      ]
    }


    var demoWorkspace = Blockly.inject('blocklyDiv',
      {
        media: 'blockly/media/',
        toolbox: toolbox
      });

    var startBlocks ={"blocks":{"languageVersion":0,"blocks":[{"type":"添加用户会话","id":",g8fJD_C.6HD9wZ*THui","x":355,"y":187,"inputs":{"VALUE":{"block":{"type":"text","id":"zPSMY@7;Z{.E{X+JE@?W","fields":{"TEXT":"程序开始运行"}}}},"next":{"block":{"type":"controls_if","id":"iT,pk#nrYYiuU8PKx;X$","inline":false,"extraState":{"hasElse":true},"inputs":{"IF0":{"block":{"type":"logic_compare","id":"T4+ttZ~C_b*QO*3rX{Em","fields":{"OP":"EQ"},"inputs":{"A":{"block":{"type":"用户输入","id":"o@rNb@2m,1jCereA^pDz"}},"B":{"block":{"type":"text","id":"/|Fut]UGF$5;,^1oyrZ.","fields":{"TEXT":"你好"}}}}}},"DO0":{"block":{"type":"text_print","id":"1o4/30[sgFM*ilp0v48=","inline":false,"inputs":{"TEXT":{"block":{"type":"发送","id":"|bJf6;$KtPy=XjT5cnnQ","inputs":{"VALUE":{"block":{"type":"text","id":"zzQT`a;U(lNXXnBbcy](","fields":{"TEXT":"你好，闻达"}}}}}}}}},"ELSE":{"block":{"type":"text_print","id":"|?MKt8g%`aXLu=ixEn4X","inline":false,"inputs":{"TEXT":{"block":{"type":"发送","id":"A3X`8{7G)$yWJjE`H$~G","inputs":{"VALUE":{"block":{"type":"用户输入","id":"iEy-%[lUSX}vAu3Y~xgB"}}}}}}}}},"next":{"block":{"type":"添加AI会话","id":"-LB?JxOhy({t)+htNW}+","inputs":{"VALUE":{"block":{"type":"text","id":"aY=xvk~..+ub7M#D,V|3","fields":{"TEXT":"程序结束运行"}}}}}}}}}]}}
    Blockly.serialization.workspaces.load(startBlocks, demoWorkspace);

    function showCode() {
      // Generate JavaScript code and display it.
      Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
      var code = Blockly.JavaScript.workspaceToCode(demoWorkspace);
      alert(code);
    }

    function runCode() {
      // Generate JavaScript code and run it.
      window.LoopTrap = 1000;
      Blockly.JavaScript.INFINITE_LOOP_TRAP =
        'if (--window.LoopTrap < 0) throw "Infinite loop.";\n';
      var code = Blockly.JavaScript.workspaceToCode(demoWorkspace);
      Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
      parent.postMessage({ from: '猫猫也会的图块化编程', data: code }, '/')
    }
    function saveCodeAsAuto() {
      // Generate JavaScript code and run it.
      window.LoopTrap = 1000;
      Blockly.JavaScript.INFINITE_LOOP_TRAP =
        'if (--window.LoopTrap < 0) throw "Infinite loop.";\n';
      var code = Blockly.JavaScript.workspaceToCode(demoWorkspace);
      Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
      parent.postMessage({ from: '猫猫也会的图块化编程_保存', data: code }, '/')
    }
    function analyzeCode() {
      // Generate JavaScript code and run it.
      window.LoopTrap = 1000;
      Blockly.JavaScript.INFINITE_LOOP_TRAP =
        'if (--window.LoopTrap < 0) throw "Infinite loop.";\n';
      var code = Blockly.JavaScript.workspaceToCode(demoWorkspace);
      Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
      parent.postMessage({ from: '猫猫也会的图块化编程_分析', data: code }, '/')
    }
  </script>

</body>

</html>